#include "config.h"
#include "intrinsics.h"
#include "fpmath.h"
#include "wavetable.h"
#include "fft.h"

fft_complex_t complex[WAVE_SIZE >> 1];

// Construct harmonic content for sawtooth
// Note: This could be any combination of harmonics, sawtooth is just an example.
// Note on fft_sym_magnitude: works with bit reversed real data, hence the symmetrical pair n&z.
void synth_sawtooth(fft_complex_t *complex, unsigned fft_bits) {
	unsigned fft_size = 1 << fft_bits;
  fft_sym_dc(complex, 0, 0);
  for(unsigned n = 1, z = fft_size - 1; n <= fft_size >> 1; n++, z--) {
    fft_sym_magnitude(complex, fft_bits, n, 0x4000000 / n, 0x4000000 / z);
  }
}

void benchmark(void) {
  unsigned fft_size = WAVE_SIZE;
  unsigned fft_bits = WAVE_BITS;

  // This loop generates a mip-mapped wavetable:
	// 1st iteration: all frequencies
	// 2nd iteration: 1/2 frequencies, 1/2 size
	// 3rd iteration: 1/4 frequencies, 1/4 size
	// etc...
	while(fft_size > 2) {
    
		// Update size and bit count
		fft_size >>= 1;
    fft_bits--;

    // Construct harmonic content
    synth_sawtooth(complex, fft_bits);

		// Perform IFFT (data is already bit-reversed)
    fft_inverse(complex, fft_size);
		
    // Copy to wavetable
    unsigned size = fft_size << 1;
    samp16bit *p_table = &wavetable[size];
    samp32bit *p_tcplx = (samp32bit*)complex;
    while(size--) *p_table++ = (*p_tcplx++) >> 16;

  }
}
